<template>
  <div id="commit" class="commit">
    <el-container class="el-container">
      <el-header :height="100" class="custom-header">
        <el-row class="header-row">
          <div style="font-size:15px;">
            杠杆&nbsp;:&nbsp;
            <el-select filterable v-model="leverage" placeholder="" allow-create style="width: 100px" size="small">
              <el-option v-for="l in leverages" :key="l" :label="l" :value="l">
              </el-option>
            </el-select>
          </div>
          <el-select filterable :filter-method="filter" v-model="goodId" placeholder="" size="small" style="width: 150px"  @click="addGoodsHistory()">
            <div v-for="{goods,pkId,collect} in filterGoodList" class="option_item">
              <el-option :key="pkId" :label="goods" :value="pkId" class="option_text">
                <span>{{ goods }}</span>
              </el-option>
              <span  @click="goodUp(pkId)" class="option_icon" >
                <el-icon v-if="!collect" class="option_icon_start"><Star /></el-icon>
                <el-icon v-else color="#F2E209" size="20" class="option_icon_start_filled"><StarFilled /></el-icon>
              </span>
            </div>
          </el-select>
          <el-radio-group v-model="period" size="small">
            <el-radio-button v-for=" {name,type} in periods" :key="type" :label="name" :value="type"></el-radio-button>
          </el-radio-group>
          <div>
            <el-date-picker
              v-model="times"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY/MM/DD ddd"
              time-format="A hh:mm:ss"
              size="small"
            />
          </div>
          <el-input clearable type="number" v-model="initialCash" style="width: 150px" placeholder="初始本金" size="small"/>
          <div>
            <el-button type="primary" size="small" @click="addRow">添加</el-button>
          </div>
          <div>
            <el-button type="success" size="small" @click="commit" :disabled="tableData.length == 0 ? true : false">开始回测</el-button>
          </div>
        </el-row>
      </el-header>
      <el-main class="el-main">
        <el-table class="table" :data="tableData" border :header-cell-style="tableHeaderStyles">
          <el-table-column prop="id" label="序号"  />
          <el-table-column prop="goods" label="品种"  />
          <el-table-column prop="period" label="周期"  />
          <el-table-column prop="initialCash" label="本金"  />
          <el-table-column prop="leverage" label="杠杆"  />
          <el-table-column prop="beginTime" label="开始时间"  />
          <el-table-column prop="endTime" label="结束时间"  />
          <el-table-column align="center" width="150">
            <template #header>
              功能
            </template>
            <template #default="scope">
              <el-button size="small" @click="removeRow(scope.$index, scope.row)" type="danger">删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import { getAllGoods,commitTestBackList } from '../apis.js'
import localStore from '../localStore.js'
import { ElMessage,ElMessageBox } from 'element-plus'
import moment from 'moment-timezone';
import { nanoid } from 'nanoid'
import { mapActions,mapState } from 'pinia';
import { tradeId,goodsTradeArray } from '../store.js'

export default{
  data(){
    return{
      times:'', //时间范围
      initialCash:undefined,//初始本金
      goodId:undefined,
      goodList:[],
      goodFilter: '', //用于筛选条件
      periods:[
        {name:'M1',type:'M1'},
        {name:'M5',type:'M5'},
        {name:'M15',type:'M15'},
        {name:'M30',type:'M30'},
        {name:'H1',type:'H1'},
        {name:'H4',type:'H4'},
        {name:'D1',type:'D1'},
        {name:'W1',type:'W1'},
        {name:'MN',type:'MN'},
      ],
      period:'M1',
      tableData:[],
      leverages:[1,10,50,100,200,500],
      leverage:500,
      // tableHeaderStyles:{
      //   backgroundColor:'#f5f7fa',
      // }
    }
  },
  computed:{
    ...mapState(tradeId, ['tradeId']),
    ...mapState(goodsTradeArray, ['goodsTradeArray']),
    filterGoodList(){
      return this.goodList.filter(v => v.goods.toLocaleLowerCase().indexOf(this.goodFilter.toLocaleLowerCase()) >= 0);
    },
  },
  methods:{
    ...mapActions(tradeId,{setTradeId:'set'}),
    ...mapActions(goodsTradeArray,{setGoodsTradeArray:'set'}),
    filter(filterStr){
      this.goodFilter = filterStr;
    },
    addGoodsHistory(){
      let history = this.getGoodsHistory() || [];
      this.goodList = this.goodList.map(v => (history.indexOf(v.pkId) >= 0 ?{...v,collect:true}:{...v,collect:false}));
      this.goodList = this.goodList.sort((good1,good2) => {
        if(good1.collect && !good2.collect){
          return -1;
        }
        else if(!good1.collect && good2.collect){
          return 1;
        }
        else if(good1.collect && good2.collect){
          return history.indexOf(good1.pkId) - history.indexOf(good2.pkId);
        }
        else{
          return 0;
        }
      });
    },
    getGoodsHistory(){
      let goods_history = localStore.getItem('goods_history');
      let history;
      if(!goods_history){
        this.setGoodsHistory([]);
        history = [];
      }
      else{
        history = JSON.parse(goods_history);
      }
      return history;
    },
    setGoodsHistory(history){
      localStore.setItem('goods_history',JSON.stringify(history));
    },
    addRow(){
      if(!this.goodList.find(v => v.pkId == this.goodId)){
        ElMessage({
          message: '缺少品种',
          type: 'error',
        });
      }
      else if(!this.times){
        //名称存在
        ElMessage({
          message: '缺少时间',
          type: 'error',
        });
      }
      else if(!this.period){
        //名称存在
        ElMessage({
          message: '缺少周期',
          type: 'error',
        });
      }
      else if(!this.initialCash){
        //名称存在
        ElMessage({
          message: '缺少本金',
          type: 'error',
        });
      }
      else if(!this.leverage){
        //名称存在
        ElMessage({
          message: '缺少杠杆',
          type: 'error',
        });
      }
      else{
        this.tableData.push({
          id:nanoid(),
          goods:this.goodList.find(v => v.pkId == this.goodId).goods,
          period:this.period,
          initialCash:this.initialCash,
          leverage:this.leverage,
          beginTime:moment(this.times[0].getTime()).format('YYYY-MM-DD HH:mm:ss'),
          endTime:moment(this.times[1].getTime()).format('YYYY-MM-DD HH:mm:ss'),
        })
      }
    },
    removeRow(index,row){
      ElMessageBox.confirm(`确认删除?`,'',{
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        showCancelButton: false	
      })
      .then(() => {
        this.tableData = this.tableData.filter(v => v.id != row.id);
       })
      .catch(() => {})
    },
    async commit(){
      try{
        let result = await commitTestBackList(this.tableData.map(v => ({...v,id:undefined,initialCash:parseInt(v.initialCash),leverage:parseInt(v.leverage)})));
        this.setTradeId(result.tradeId);
        this.setGoodsTradeArray(result.goodsTradeArray);
        this.$nextTick(() => {
          this.$router.push({name:'testBackRun'});
        });
      }
      catch(e){
        ElMessage({
          message: '提交失败',
          type: 'error',
        });
      }
    },
    goodUp(pkId){
      let history = this.getGoodsHistory();
      if(history.indexOf(pkId) >= 0){
        history = history.filter(v => v != pkId);
      }
      else{
        history.push(pkId);
      }
      this.setGoodsHistory(history);
      this.addGoodsHistory();
    },
  },
  async mounted(){
    //获取品种列表
    let goodsInfo = await getAllGoods();
    this.goodList = goodsInfo.data.data;
    // window.moment = moment;
  }
}
</script>

<style scoped>
body {
  margin: 0;
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background-color: #f2f3f5;
}

div,
p {
  box-sizing: border-box;
}

p {
  margin: 0;
}

.commit {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  flex-wrap: wrap;
}
.el-container{
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}
.custom-header{
  padding: 10px 20px;
  padding-bottom: 0px;
}
.option_item{
  display: flex;
  width: 100%;
}
.option_text{
  flex-grow: 1;
}
.option_icon{

}
.option_icon_start_filled{
  padding: 0px 11px;
  line-height:100%;
  height:100%;
}
.option_icon_start{
  padding: 0px 15px;
  line-height:100%;
  height:100%;
}
.header-row{
  display: flex;
  justify-items: center;
  justify-self: center;
}
.header-row>*:nth-child(n+2){
  padding-left: 20px;
}
.el-main{
  padding-left: 20px;
  padding-right: 20px;
  padding-top: 20px;
}
.table{
  /* padding: 20px; */
  width:calc(100% - 20px * 2);
}
</style>
